package zju.ccnt.rest.service.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * Created by zha on 14/11/6.
 * validator for number_like string input
 * current support:
 *        phone: like 123-12345678, 1234-1234567, 1234-12345678
 *        ip: {0-255}.{0-255}.{0-255}.{0-255}
 */
public class NumericalLikeValidator implements ConstraintValidator<ValidNumericalLike, String> {

    //the final regex patter string
    private static final String PHONE_PATTERN = "\\d{3}-\\d{8}|\\d{4}-\\{7,8}|\\d{11}";
    private static final String IP_PATTERN = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$";

    private Pattern pattern;

    public enum NumericalEnum{
        //Instances of the enum
        PHONE(PHONE_PATTERN),
        IP(IP_PATTERN);

        private String regexPattern;

        public String getRegexPattern() {
            return regexPattern;
        }

        private NumericalEnum(String pattern){
            this.regexPattern = pattern;
        }
    }

    @Override
    public void initialize(ValidNumericalLike validNumericalLike) {
        NumericalEnum type = validNumericalLike.type();
        pattern = Pattern.compile(type.getRegexPattern(), Pattern.CASE_INSENSITIVE);
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (pattern.matcher(s).matches()) {
            return true;
        }
        return false;
    }
}
